/*
 * @name: 
 * @version: 1.1.1
 * @Author: 刘大可
 * @Date: 2022-06-15 09:55:53
 * @LastEditors: 刘大可
 * @LastEditTime: 2022-11-08 14:43:40
 */
var app = getApp();

module.exports ={

    data:{
        formData:{
        },
        amount:0, // 实际金额 由后台计算
        user_price:0, // 用户输入金额
        unique:"",
        express_info:[

        ],
        specs:[],
        start:"",
        u:{
            name:"",
            phone:""
        }
    },
    watch:{
        express_num(val) {
            if (this.userInfo.is_vip == 1) {
                var totals = (this.form.total - this.form.MinRunPrice).toFixed(2);
            } else {
                var totals = this.form.total;
            }
            if (totals < this.form.y_money) {
                this.form.y_money = 0.00
                this.y_money = 0.00
                this.form.co_title = ""
                this.form.co_id = ""
            }
            // this.calculate()
        },
        weightindex(val){
            this.calculate()
        },
        form(val){
            // console.log("val");
            // console.log(val);
            // 如果用户的价格等于-1 就把基础费给他
            console.log(this.userInfo.is_vip);
            if ((this.type == 3 && this.total_prices !=0)||this.type!=3) {
                this.calculate()
            }

            // if (this.userInfo) {
            //     if (this.user_price == 0) {
            //         if (this.userInfo.is_vip == 0) {
            //             this.user_price = val.MinRunPrice
            //         }
            //     }
            // }
            

        },
        
        user_price(val){
            this.custom=val
            // this.calculate()
        },
        /**
         * 
         * @param {*} val 
         */
        total_prices(val) {
            // this.custom = val
            this.calculate()
        },
        express_info:{

            handler(val) {
                console.log(val)
                this.calculate()
            },
            // 这里是关键，代表递归监听 demo 的变化
            deep: true
            
        },
        // user_price(e){
        //     console.log(e.toFixed(2));
        // }
       
        
    },
    methods: {
        addForm(init=0){
            let index=0
            let item = this.specs[index]
            let data = {
                specs: item.name,
                specsIndex: index,
                "price": item.price,
                "code": ""
            }

            if (init==1) {
                this.express_info=[data]
            }else{
                this.express_info.push(data)

            }
           


        },
        changeExpress(e){
            console.log(e);
            let index = e.currentTarget.dataset.index
            let item = this.specs[e.detail.value]
            console.log(index);
            console.log(item);

            this.express_info[index].price = item.price
            this.express_info[index].specs = item.name
            this.express_info[index].specsIndex = e.detail.value
        },
        jia(index){
            let item =this.express_info[index]
            item.price = (Number(item.price) + 1).toFixed(2)


        },
        jian(index){
            let item = this.express_info[index]
            let price = (Number(item.price) - 1).toFixed(2)
            console.log(price);
           
            if (price < Number(this.specs[item.specsIndex].price)) {
                // this.tips.tips("你减个Der!")
                // this.tips.tips("不能再减了┭┮﹏┭┮!")
                this.tips.tips("不能再减了!")
            } else{
                item.price =price

            }
        },
        checkPrice(e){
        
            let index = e.currentTarget.dataset.index
            let price = e.detail.value
            let i = this.express_info[index].specsIndex
            let item = this.specs[i]

            if (price<item.price) {
               this.tips.tips("输入价格低于初始价格");
               this.express_info[index].price=item.price
            }

            
            
            // (Number(item.price) - 1).toFixed(2)

            
        },
        del(index){
            this.express_info.splice(index)
        },
        /**
         * @name 调用接口计算价格
         */
        async calculate(){
            var goods_det = uni.getStorageSync('json');
            let express_info="";
            if (this.type==1|this.type==2) {
                express_info = JSON.stringify(this.express_info)
            }

           
            let res = await this.request(this.psType == 0 ?"RenIndex/calculatePrice":'RenIndex/self_calculatePrice', {
                // let res=await this.request('RenIndex/calculatePrice', {
                    s_id: uni.getStorageSync('schoolId'),
                    weight: this.weightindex,
                    u_id:uni.getStorageSync('u_id'),
                    // weight: this.weight[this.weightindex],
                    module_id: uni.getStorageSync('module_id'),
                    express_num: this.express_num,
                    is_vip: this.userInfo.is_vip,
                    input_price:this.user_price,
                    y_money: this.y_money,
                    food_money:this.total_prices||0,
                    store_id: this.bid||"",
                goods_det: JSON.stringify(goods_det),
                    express_info

                // openid: uni.getStorageSync('openid') ? uni.getStorageSync('openid') :
                //     'nologinuser'
            })
            console.log(res);
            this.amount = res.data.data.t_money
            this.unique = res.data.data.unique
            // this.form={
            //     ...this.form,
            //     unique: res.data.data.unique
            // }
        },
        /**
         * @name 关闭弹窗 
         * @update 2022年06月15日11:31:34
         * @param {*} e 
         * @returns 
         */
        hideModal(e) {
            if (this.modalName == 'ChooseModal') {
                console.log('执行这里');

                if (Number(this.form.total) < Number(this.form.MinRunPrice)) {
                    uni.showToast({
                        title: '最少费用是' + this.form.MinRunPrice,
                        icon: 'none'
                    });
                    return;
                    this.setData({
                        form: { ...this.form, total: this.form.MinRunPrice }
                    });
                }
            }
            var mny = /^[0-9]*(\.[0-9]{1,2})?$/;
            if (!mny.test(this.custom)) {
                
                // this.custom = this.amount
                // this.user_price = this.amount
                
                app.globalData.util.message('输入金额无效！', '', 'error');
                return false
            }

            console.log('custom', this.custom);
            console.log('最低金额', this.form.MinRunPrice);
            console.log('优惠金额', this.y_money);

            if (this.y_money > this.custom) {
                app.globalData.util.message('金额不可低于优惠券金额', '', 'error');
                return;
            }

            if (this.custom == undefined) {
                app.globalData.util.message('请输入正确的数字', '', 'error');
                return;
            }

            if (this.custom < 0) {
                app.globalData.util.message('输入金额有误', '', 'error');
                return;
            }

            var zong = Number(Number(this.form.MinRunPrice) + Number(this.extra_price) + Number(this.extra_jian_price)).toFixed(2);
            zong = this.form.MinRunPrice
            console.log('不低于', zong); // if(Number(this.data.custom)<Number(this.data.form.MinRunPrice))

            if (Number(this.custom) < zong) {
                app.globalData.util.message('金额不能低于' + zong, '', 'error');
                return;
            } else {
                this.setData({
                    form: { ...this.form, total: this.custom }
                });
            }

            this.setData({
                modalName: null
            });
        },

        getuserInfo() {
            var that = this;
            app.globalData.util.request({
                url: 'WechatUser/view',
                data: {},
                success(res) {
                    that.setData({
                        userInfo: res.data.data
                    });
                    if (res.data.data.is_vip==1) {
                        that.user_price=0
                    }
                    that.u={
                        phone:res.data.data.phone
                    }
                    // that.getDefaultPrice()
                    console.log('that.type', that.type);
                    
                    if (that.type == 3) {
                        that.jise();
                    }else{
                        that.calculate()
                    }

                }
            }, true);
        },


        async  daodian(){
            var self = this;
            var that = this;
            if (self.is_click) {
                self.setData({
                    is_click: false
                });
                app.globalData.util.request({
                    url: 'Order/userBuy',
                    data: {
                        s_id: uni.getStorageSync('schoolId'),
                        food_money: this.form.guess_prcie,
                        express_num: this.express_num,
                        store_id: uni.getStorageSync('store_id'),
                        remarks: this.form.showText,
                        // qu_latitude: this.buyaddress.location_x ? this.buyaddress.location_x : uni.getStorageSync('city').location.lng,
                        // qu_longitude: this.buyaddress.location_y ? this.buyaddress.location_y : uni.getStorageSync('city').location.lat,
                        qu_addres: this.buyaddress.address,
                        weight: this.weight[this.weightindex],
                        sex_limit: this.sexindex,
                        // start_time: this.storeType == 0 ? (this.tlist[0][this.multiIndex[0]] + ' ' + this.tlist[1][this.multiIndex[1]]) : 0,
                        food_money: this.total_prices,
                        ...this.form,
                        sh_school: uni.getStorageSync('schoolId'),
                        openid: uni.getStorageSync('openid'),
                        out_time_num: this.form.out_time_num,
                        img: this.picList,
                        attach_file: '',
                        // img: img,
                        good_details: this.good_details,
                        goods_list: JSON.stringify(uni.getStorageSync('json')),
                        unique: this.unique,
                        // ordertime: this.timeList[this.ordertime],
                        givetype: this.storeType,
                        arrival_time: that.arrival_time,
                        is_self_lifting: that.psType,
                        sh_name:this.u.name,
                        phone:this.u.phone
                    },

                    success(res) {
                        console.log('1111111', res);

                        if (res.data.msg == '下单成功，无需支付' || res.data.msg == '会员已抵扣') {
                            uni.showToast({
                                title: "下单成功",
                                // icon: 'loading',
                                icon: 'success',
                                duration: 3000
                            });
                            if (res.data.data.order.is_store_delivery == 2) {
                                app.globalData.util.request({
                                    url: 'Order/StorePrint',
                                    data: {
                                        o_id: res.data.data.order.id
                                    }
                                });
                            }
                            else {
                                app.globalData.util.request({
                                    url: 'MsgSubscribe/toAllRider',
                                    data: {
                                        ordersn: res.data.data.order.ordersn
                                    }
                                });
                            }
                            setTimeout(function () {
                                uni.navigateTo({
                                    url: '/gc_school/pages/order/index?type=1'
                                });
                            }, 2000);
                            uni.removeStorage({
                                key: 'json'
                            });
                        } else {
                            console.log(res.data.data.ordersn);
                            uni.requestPayment({
                                timeStamp: res.data.data.paydata.timestamp.toString(),
                                nonceStr: res.data.data.paydata.nonceStr,
                                package: res.data.data.paydata.package,
                                signType: 'MD5',
                                paySign: res.data.data.paydata.paySign,
                                success: function (resu) {
                                    console.log('success');
                                    console.log(res.data.data);
                                    // app.globalData.util.request({
                                    //     url: 'MsgSubscribe/toAllRider',
                                    //     data: {
                                    //         ordersn: res.data.data.order.ordersn
                                    //     }
                                    // });
                                    setTimeout(function () {
                                        uni.navigateTo({
                                            url: '/gc_school/pages/order/index?type=1'
                                        });
                                    }, 2000);
                                },
                                fail: function (res) {
                                    console.log('fail');
                                }
                            });
                        }
                    },

                    complete() {
                        self.setData({
                            is_click: true
                        });
                    } // fail(e) {
                    //     console.log('弹框1111', e)
                    // }
                }, true);
            } else {
                uni.showToast({
                    title: '请稍后重试...',
                    icon: 'none'
                });
            }
        }
    },

}